package com.链表2;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;

/**
 * 给出两个 非空 的链表用来表示两个非负的整数。其中，它们各自的位数是按照 逆序 的方式存储的，并且它们的每个节点只能存储 一位 数字。
 *
 * 如果，我们将这两个数相加起来，则会返回一个新的链表来表示它们的和。
 *
 * 您可以假设除了数字 0 之外，这两个数都不会以 0 开头。
 *
 * 示例：
 *
 * 输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)
 * 输出：7 -> 0 -> 8
 * 原因：342 + 465 = 807
 */
public class 两数相加 {
    static class Solution {
        public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
            ListNode pr1 = new ListNode(-1),pr2 = pr1;
            int next = 0;
            while (l1 != null || l2 != null){
                int num1 = l1 == null ? 0 : l1.val;
                int num2 = l2 == null ? 0: l2.val;
                int sum = num1 + num2 + next;
                if(sum > 9){
                    next = 1;
                    pr2.next = new ListNode(sum%10);
                    pr2 = pr2.next;
                }
                else{
                    pr2.next = new ListNode(sum);
                    next = 0;
                    pr2 = pr2.next;
                }
                    if(l1 != null) {
                        l1 = l1.next;
                    }
                    if(l2 != null) {
                        l2 = l2.next;
                    }
            }
            //进位
            if(next == 1){
                pr2.next = new ListNode(1);
            }
            return pr1.next;

        }

        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
           String num1 = conver(reserve(l1));
           String num2 = conver(reserve(l2));

            String sum2 = String.valueOf(0);
            ListNode l3 = new ListNode(-1),l4 = l3;
            for(int i = sum2.length()-1;i>=0;i--){
                int num = Integer.parseInt(String.valueOf(sum2.charAt(i)+""));
                l4.next = new ListNode(num);
                l4 = l4.next;
            }
            return l3.next;
        }
        //反转链表
        public ListNode reserve(ListNode head){
            ListNode pre = null,cur =head;
            while (cur != null){
                ListNode tmp = cur.next;
               cur.next = pre;
               pre = cur;
                cur = tmp;
            }
            return pre;
        }

        /**
         * 转换数字
         * @param head
         * @return
         */
        public String conver(ListNode head){
            ListNode cur = head;
            StringBuilder builder = new StringBuilder();
            while (cur != null){
                builder.append(cur.val);
                cur = cur.next;
            }
            return builder.toString();
        }
    }

    public static void main(String[] args) {
        MyLinkedList link = new MyLinkedList(new int[]{9,9});
        MyLinkedList link2 = new MyLinkedList(new int[]{9});
        Solution solution = new Solution();
        ListNode node = solution.addTwoNumbers2(link.head.next,link2.head.next);


    }
}
